/**
 * 
 */
package org.stars.database.diagnostic;

import java.sql.Connection;
import java.sql.PreparedStatement;

import org.stars.database.ConnectionPool;
import org.stars.database.ConnectionPoolManager;

/**
 * @author Francesco Benincasa (908099)
 * 
 */
public class DatabaseDiagnostic {
	/**
	 * istanza
	 */
	protected static DatabaseDiagnostic instance;

	/**
	 * Costruttore
	 */
	protected DatabaseDiagnostic() {
	}

	/**
	 * Get instance
	 * 
	 * @return
	 */
	public static DatabaseDiagnostic getInstance() {
		if (instance == null) {
			instance = new DatabaseDiagnostic();
		}

		return instance;
	}

	/**
	 * Elenca tutti i connection pool in html
	 * 
	 * @return
	 */
	public String toHtmlTable() {
		ConnectionPoolManager cpm = ConnectionPoolManager.getInstance();

		StringBuffer buffer = new StringBuffer();

		buffer.append("<table>\n");

		for (ConnectionPool cp : cpm.getAllConnectionPool().values()) {
			buffer.append("<tr>\n");

			buffer.append("<td>");
			buffer.append(cp.getName());
			buffer.append("</td>");

			buffer.append("<td>");
			buffer.append(cp.getInfo());
			buffer.append("</td>");

			buffer.append("<td>");
			buffer.append(cp.getClass());
			buffer.append("</td>");

			buffer.append("</tr>\n");
		}

		buffer.append("</table>\n");

		return buffer.toString();
	}
	
	/**
	 * Testa la connessione di default con una query definita dall'utente.
	 * 
	 * @param sql
	 * 		query da testare
	 * @return
	 * 		<code>true</code> se tutto e' andato a buon fine.
	 */
	public boolean testDefaultConnection(String sql)
	{
		boolean ret=false;
		
		Connection cn=null;
		PreparedStatement ps=null;
		try {
			cn	=	ConnectionPoolManager.getInstance().getConnection();
			ps	=	cn.prepareStatement(sql);
			
			ps.execute();
						
			ret=true;
		} catch (Exception e) {
		
		}
		finally
		{
			if (ps!=null) { try { ps.close(); } catch(Exception e1) {} }
			if (cn!=null) { try { cn.close(); } catch(Exception e2) {} }
		}
		return ret;
	}
}
